import java.util.Arrays;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * @author: zhangxupeng
 * @date:2019/5/10
 * @Email: zhangxupeng@bilibili.com
 **/
public class TestStreamCloseException {
    public static void main(String[] args) {
        //异常
//        closeStreamError();
        //正确的使用
        correctReuseStream();
    }

    /**
     * 重复使用Stream，正确使用通过Supplier
     */
    private static void correctReuseStream() {
        String[] array = {"a", "b", "c", "d", "e"};

        Supplier<Stream<String>> streamSupplier = () -> Stream.of(array);

        //get new stream
        streamSupplier.get().forEach(x -> System.out.println(x));

        //get another new stream
        long count = streamSupplier.get().filter(x -> "b".equals(x)).count();
        System.out.println(count);
    }

    /**
     * 抛出异常
     */
    private static void closeStreamError() {
        String[] array = {"a", "b", "c", "d", "e"};
        Stream<String> stream = Arrays.stream(array);

        // loop a stream
        stream.forEach(x -> System.out.println(x));

        // reuse it to filter again! throws IllegalStateException
        long count = stream.filter("b"::equals).count();
        System.out.println(count);
    }
}
